const app = getApp()
var flag0 = false;


Page({

  /**
   * 页面的初始数据
   */
  data: {
    texts: "",
    
    tempFilePaths: [],
    name:"",
    phone:"",
    score:0.0,
    picture:null,

    icontype: ["info_circle", "info"],
    word:"以上信息将用于用户接单时方便联系，请正确填写。初始得分为5分，而您服务的对象将可以根据您的服务质量为您打分。系统将按照一定的计算公式为您计算评分，当您的评分低于2.5分时，您将不能再接单，请注意！"

  },

  //点击提交
  formSubmit: function (e) {
    var that = this;
    var warn = "";//弹框时提示的内容
    var flag = true;//判断信息输入是否完整
    //判断的顺序依次是：姓名-手机号
    if (e.detail.value.name == "") {
      warn = "请输入您的姓名";
    } else if (!(/^1(3|4|5|7|8)\d{9}$/.test(e.detail.value.phone))) {
      warn = "请正确输入您的电话";
    } else if (that.data.tempFilePaths.length == 0) {
      warn = "请上传个人照片";
    } 
    else {

      flag = false;//若必要信息都填写，则不用弹框，且页面可以进行跳转      
    
      /////////////////////////////////////////////上传图片 

      console.log('图片路径：', that.data.tempFilePaths)
      /*var picture = that.data.tempFilePaths[0].split("/");
      that.data.tempFilePaths[0] = "http://tmp/" + picture[picture.length - 1];
      console.log('图片路径1：', that.data.tempFilePaths)*/
        var images_list = []; //设置了一个空数组进行储存服务器端图片路径       
          if(flag0==true){
          wx.uploadFile({
            url: app.globalData.baseUrl + '/worker/workerupload',
            filePath: that.data.tempFilePaths[0],
            name: 'file',
            formData: null,
            success: function (res) {
              console.log(res.data)
              //console.log(res.data)
              //后端返回图片上传到服务器上边的地址的json
              //图片json转换数组
              var jsonObj = JSON.parse(res.data)
              console.log(jsonObj.url)
              images_list.push(jsonObj.url);
              if (1 == images_list.length) {//只有当图片全部上传成功才能提交表单，因为表单只需要提交一次
                var images_str = images_list.join(",")//把存放图片地址的数组转化为以逗号分隔的字符串
                console.log("images_str:", images_str)
                wx.request({
                  url: app.globalData.baseUrl + '/worker/insertworker',
                  method: 'POST',
                  data: {
                    name: e.detail.value.name,
                    phone: e.detail.value.phone,
                    openId: wx.getStorageSync("openid"),
                    score: e.detail.value.score,                           
                    picture: images_str
                  },
                  header: {
                    "Content-Type": "application/x-www-form-urlencoded" // 默认值
                  },
                  success(res) {//success只能说明接口调取并返回成功，并不是代表信息上传成功，还需要判断返回的信息
                    var result = res.data.success                   
                    var toastText = "操作成功！";
                    if (result != true) {
                      toastText = "信息未修改" ;
                    }
                    wx.showToast({
                      title: toastText,
                      icon: '',
                      duration: 2000
                    });
                    if (result == true) {
                      //that.onShow();
                      var toastText = "操作成功！";
                    }

                    

                  }
                })
              }

            },
            fail: function (error) { }
          })
          }else{
            console.log("进来了:")
            var picture = that.data.tempFilePaths[0].split("/");
            var pictureUrl = '/' + picture[picture.length - 3] + '/' + picture[picture.length - 2] +'/'+ picture[picture.length - 1];
            console.log('图片路径1：', pictureUrl)
            wx.request({
              url: app.globalData.baseUrl + '/worker/insertworker',
              method: 'POST',
              data: {
                name: e.detail.value.name,
                phone: e.detail.value.phone,
                openId: wx.getStorageSync("openid"),
                score: e.detail.value.score,
                picture: pictureUrl
              },
              header: {
                "Content-Type": "application/x-www-form-urlencoded" // 默认值
              },
              success(res) {//success只能说明接口调取并返回成功，并不是代表信息上传成功，还需要判断返回的信息
                var result = res.data.success
                var toastText = "操作成功！";
                if (result != true) {
                  toastText = "信息未修改" ;
                }
                wx.showToast({
                  title: toastText,
                  icon: '',
                  duration: 2000
                });
                if (result == true) {
                  //that.onShow();
                  var toastText = "操作成功！";
                }



              }
            })
            flag0 =false;

          }
        

      
    }
    //如果信息填写不完整，弹出输入框
    if (flag == true) {
      wx.showModal({
        title: '提示',
        content: warn
      })
    }
  },


  onShow:function(e){
    var that=this;
    wx.request({
      url: app.globalData.baseUrl + '/worker/getworker',
      method: 'GET',
      data: { "openId": wx.getStorageSync('openid') },//传入的参数
      success: function (res) {
        var worker = res.data.worker;
        console.log("worker0:", worker)
        var userInfo = wx.getStorageSync('userInfo');
        that.setData({ userInfo: userInfo });
        
        if (worker == "null") {
          console.log("进来这里")
          /* var toastText = '没有未读消息' + res.data.errMsg;
           wx.showToast({
             title: toastText,
             icon: '',
             duration: 2000
           });*/
        } else {         
          var picture=[];
          picture.push(app.globalData.baseUrl + worker.picture);
          that.setData({
            name: worker.name,
            phone: worker.phone,
            score: worker.score,
            //tempFilePaths: picture
          });
        }
      }
    })
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    wx.request({
      url: app.globalData.baseUrl + '/worker/getworker',
      method: 'GET',
      data: { "openId": wx.getStorageSync('openid') },//传入的参数
      success: function (res) {
        var worker = res.data.worker;
        console.log("worker0:", worker)
        var userInfo = wx.getStorageSync('userInfo');
        that.setData({ userInfo: userInfo });

        if (worker == "null") {
          console.log("进来这里")
          /* var toastText = '没有未读消息' + res.data.errMsg;
           wx.showToast({
             title: toastText,
             icon: '',
             duration: 2000
           });*/
        } else {
          var picture = [];
          picture.push(app.globalData.baseUrl + worker.picture);
          that.setData({
            name: worker.name,
            phone: worker.phone,
            score: worker.score,
            tempFilePaths: picture
          });
        }
      }
    })
  },
  exit: function (e) {
    wx.showModal({
      title: '提示',
      content: '是否确认退出',
      success: function (res) {
        if (res.confirm) {
          // console.log('用户点击确定')
          wx.removeStorageSync('userInfo');
          //页面跳转
          wx.redirectTo({
            url: '../user/user',
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  
  /**
   * 上传图片方法
   */
  upload: function () {
    let that = this;
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: res => {
        wx.showToast({
          title: '正在上传...',
          icon: 'loading',
          mask: true,
          duration: 1000
        })
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        let tempFilePaths = res.tempFilePaths;

        that.setData({
          tempFilePaths: tempFilePaths
        })
        flag0=true;
        /**
         * 上传完成后把文件上传到服务器
         */
        var count = 0;
        for (var i = 0, h = tempFilePaths.length; i < h; i++) {
          //上传文件
          /*  wx.uploadFile({
              url: HOST + '地址路径',
              filePath: tempFilePaths[i],
              name: 'uploadfile_ant',
              header: {
                "Content-Type": "multipart/form-data"
              },
              success: function (res) {
                count++;
                //如果是最后一张,则隐藏等待中  
                if (count == tempFilePaths.length) {
                  wx.hideToast();
                }
              },
              fail: function (res) {
                wx.hideToast();
                wx.showModal({
                  title: '错误提示',
                  content: '上传图片失败',
                  showCancel: false,
                  success: function (res) { }
                })
              }
            });*/
        }

      }
    })
  },
  /**
   * 预览图片方法
   */
  listenerButtonPreviewImage: function (e) {
    let index = e.target.dataset.index;
    let that = this;
    console.log(that.data.tempFilePaths[index]);
    console.log(that.data.tempFilePaths);
    wx.previewImage({
      current: that.data.tempFilePaths[index],
      urls: that.data.tempFilePaths,
      //这根本就不走
      success: function (res) {
        //console.log(res);
      },
      //也根本不走
      fail: function () {
        //console.log('fail')
      }
    })
  },
  /**
   * 长按删除图片
   */
  deleteImage: function (e) {
    var that = this;
    var tempFilePaths = that.data.tempFilePaths;
    var index = e.currentTarget.dataset.index;//获取当前长按图片下标
    wx.showModal({
      title: '提示',
      content: '确定要删除此图片吗？',
      success: function (res) {
        if (res.confirm) {
          console.log('点击确定了');
          tempFilePaths.splice(index, 1);
        } else if (res.cancel) {
          console.log('点击取消了');
          return false;
        }
        that.setData({
          tempFilePaths
        });
      }
    })
  }
})
